﻿var g_vIndicatorStrs=[];
var g_vIndicatorXmlDoc='';
function getIndicatorFlash()
{
    if (typeof(g_vIndicatorFlash)=="undefined") 
    {
        g_vIndicatorFlash="indicatorchart";
    }
    return g_vIndicatorFlash;
}
function OnIndicatorFlashReady(id)
{
   //setTimeout("loadIndicatorFlashData('"+id+"')",500);
   loadIndicatorFlashData(id);
}
function printData(xArray)
{ 
    //var vLabCheckNames=["checkid", "chartindex","axisindex","desc","checkid","intro","name","min","max","normalmin","normalmax","shortname","measureunit","limitvalue","gridvalues"];
    var oParent = _$("indicator_list");	
    if (oParent==null) return ;
    var g_ids=[] ;
    var sHtml = document.body.innerHTML.between("<!--TP.LIST","TP.LIST-->");
    var mapName=[
				['checkid','<%id%>',function(v){g_ids.push(v);return v;}],
				['measureunit','<%measureunit%>'],
				['name','<%name%>',function(v){return v.asccutex(16)}],
				['checkid','<%indicatorid%>',function(v){ return "ID_INDICATOR_"+v;}],
				[['limitvalue','measureunit'],'<%desc%>',function(v){ var tmp=v[0].split('@');return "提示：正常范围在"+tmp[0]+v[1]+"与"+tmp[1]+v[1]+"之间"}]
				//['', '<%allids%>', function(v) { alert(g_ids.join(",")); return g_ids.join(","); } ]
				];

    showData(xArray, oParent, sHtml, mapName);
    
   _$("ID_SUBMIT_ALL").onclick=function(){OnAddIndicatorHistorys(g_ids);}
}

function printIndicatorHistoryData(iPageNo, iPageNum, iTotal)
{ 
	var oParent = _$("indicator_history");	
    if (oParent==null) return ;
	var xResult=g_vIndicatorXmlDoc.getElementsByTagName("result")[0];
	var sHtml = document.body.innerHTML.between("<!--TP.LIST","TP.LIST-->");
    var xLabChecks = xResult.getElementsByTagName("labchecks")[0].getElementsByTagName("labcheck");
	if(xLabChecks.length < 1 ) return ;
	var measureUnit = xLabChecks[0].getAttribute("measureunit");
    var mapName=[
					['id','<%id%>'],
					['indicatorid','<%measureunit%>', function(v){ return measureUnit;}],
					['date','<%date%>',function(v){ return parseDate(v).toCommonString();}],
					['value','<%value%>']
				];
    var iStart = (iPageNo-1)*iPageNum ;
	var iEnd   = iStart + iPageNum ;
	iEnd = iEnd > iTotal ? iTotal : iEnd;
	
	showXmlNode(xResult, oParent, "indicatorhistory",sHtml, mapName, iStart, iEnd);
    iTotalPageNum = Math.ceil(iTotal/iPageNum);      
    showPage(iPageNo,iTotalPageNum,function(n){return "javascript:printIndicatorHistoryData("+n+","+iPageNum+","+iTotal+");";},document.getElementById("ID_page"),0);
}

function formatIndicatorFlashData(startDate,endDate, bForce)//id=0,生成所有的，
{
    function createIndicatorText(id)
    {
        var flashDiv = _$(getIndicatorFlash()+id);
        if (flashDiv == null || _$("_INDICATOR_TEXT_CONTAINER_"+id) != null)   return ;
        var flashDivContainer = flashDiv.parentNode ;
        var flashText = document.createElement("<div>");
        flashText.className="_INDICATOR_TEXT_CONTAINER_";
        flashText.id = "_INDICATOR_TEXT_CONTAINER_"+id;
        flashDivContainer.insertBefore(flashText, flashDiv);
        return function(p)
        {
            var flashText=_$("_INDICATOR_TEXT_CONTAINER_"+id);
            flashText.innerHTML += p ;
        }
    }
    var vLabCheck = [];
    var vIndicators=[];
    var vCharts = {};
    g_vIndicatorStrs=[];
    var xResult = g_vIndicatorXmlDoc.getElementsByTagName("result")[0];
    var xLabChecks = xResult.getElementsByTagName("labchecks")[0].getElementsByTagName("labcheck");
    var xIndicatorHistories =xResult.getElementsByTagName("indicatorhistories")[0].getElementsByTagName("indicatorhistory");
    var now = parseDate(xResult.getAttribute("now"));
    g_vNow=now;
    var confirmDate = parseDate(xResult.getAttribute("confirmdate"));
    if (typeof(endDate)=="undefined") endDate = now ;
    if(typeof(startDate)=="undefined") {startDate = parseDate(xResult.getAttribute("diseasestart"));bForce=false;}
        
    var startValue = 0 ;
    //format labcheck
    var vLabCheckNames=["checkid", "chartindex","axisindex","desc","checkid","intro","name","min","max","normalmin","normalmax","shortname","measureunit","limitvalue","gridvalues"];
    for(var i=0;i<xLabChecks.length;++i) 
    {
        var checkid=xLabChecks[i].getAttribute("checkid");
        vLabCheck[checkid] = xml2array(xLabChecks[i],vLabCheckNames);
        var vContainLabel = vCharts[vLabCheck[checkid]["chartindex"]] ;
        if (typeof(vContainLabel) == "undefined") 
        {
            vContainLabel = [];
            vContainLabel[0] = checkid;
            vCharts[vLabCheck[checkid]["chartindex"]] = vContainLabel ;
        }
        else
        {
            vContainLabel.push(checkid) ;
        }
    }
    
    var bgcolor='"bg_colour": "#FFFFFF"';
    if(xLabChecks.length==0)
    {
        var iUin=GetUin();
        var iParamUin=getURLParam("uid",g_sUrl);
        if( _$(getIndicatorFlash()+"1") == null ) return false ;
        if (iUin>0 && iUin!= iParamUin) _$(getIndicatorFlash()+"1").parentNode.innerHTML="<div class='NO_RECORD_CHART'>该用户尚未添加相关信息</div>";
        else _$(getIndicatorFlash()+"1").parentNode.innerHTML="<div class='NO_RECORD_CHART'>请您<a class='NO_RECORD_CHART_A' href='/Pages/Alpha/SymptomHistory/Index.aspx'>添加</a>相关信息</div>";
        return false;
    }
    //format indicator history        
    var vIndicatorName=["surveyid","date","value","indicatorid","id"];
    var curDate ;
    for(var i=0;i<xIndicatorHistories.length;++i)
    {
        vIndicators[i] = xml2array(xIndicatorHistories[i],vIndicatorName);
        curDate = parseDate(vIndicators[i]["date"]);
        if (typeof(bForce)=="undefined" || !bForce) 
        {
            if ( curDate<startDate ) startDate = curDate ;
        }
    }
    if (typeof(bForce)=="undefined" || !bForce) 
    {
        if ( curDate<startDate ) startDate = curDate ;
    }
    
    printData(vLabCheck);
    printIndicatorHistoryData(1, 10, vIndicators.length);
    //format the xaxis labels
    var xLabels = [];
    var iCur=4;

    var vXDistance = Math.ceil(distanceDate(startDate,endDate)/(iCur-1.0));//alert("distance:"+distanceDate(startDate,endDate)+"unit:"+vXDistance);
    --iCur;
    curDate = endDate;
    do 
    {
        xLabels[iCur] = curDate.toCommonString();
        startDate = curDate ;	
        curDate = getNextDay(curDate, -vXDistance);
    } while(--iCur >=0 );
    
   
    var xUnit = (distanceDate(startDate, endDate)+0.0)/(xLabels.length-1) ;
    //format the yaxis
    
    iCur=0;
    for(var chartindex in vCharts)
    {
        var labChecks = vCharts[chartindex];
        var sTitle='"title":{"text":"'+'","style": "{font-size: 20px;color:#0000ff;font-family:Verdana;text-align:center}"}';
        //format yAxis
        var YAxisValues={};
        var YAxisLabels={};
        var ElementValues ={};
        //对于yaxis和yaxiss
        for(var k=0; k<labChecks.length; ++k)
        {
            var sIndicatorId=vLabCheck[labChecks[k]]["checkid"];
            YAxisLabels[sIndicatorId]=vLabCheck[labChecks[k]]["gridvalues"].split(";");
            YAxisValues[sIndicatorId]=[];
            ElementValues[sIndicatorId]=[];
            for(var m=0;m<YAxisLabels[sIndicatorId].length;++m) 
            {
                YAxisValues[sIndicatorId][m]=parseFloat(YAxisLabels[sIndicatorId][m]); 
            }
        }
        
        //format Element for each chart
        var vIndicator ;
        var date;
        var vXValue ;
        for(var k=0; k<vIndicators.length;++k)
        {
            vIndicator=vIndicators[k];
            var sIndicatorId = vIndicator["indicatorid"];
            if (labChecks.find(sIndicatorId) == null) 
                continue ;
            date=parseDate(vIndicator["date"]);
            if (date<startDate) continue ;
            if (date>endDate) break;
            vXValue = distanceDate(startDate,date)/xUnit ;
            vXValue = Math.max(0.001, vXValue);
            ElementValues[sIndicatorId].push('{"value":'+getValueByArray(YAxisValues[sIndicatorId],parseFloat(vIndicator["value"]))/*+',"colour":"'+getChartColor(parseInt(sIndicatorId))*/+',"tip":"'+vLabCheck[sIndicatorId]["name"]+"<br>"+vIndicator["value"]+vLabCheck[sIndicatorId]["measureunit"]+"<br>"+date.toCommonString()+'","x":'+vXValue+'}'); 
        }
        
        var sElementValues=[];
        var YAxiss=[];
        var sYAxis;
        var iCurIndicator=0;
        var _createIndicatorText = createIndicatorText(parseInt(chartindex));
        for(var sIndicator in ElementValues)
        {
           sElementValues[iCurIndicator]= '"type":"line_dot","colour":"'+getChartColor(iCurIndicator)+'","font-size":12,"width":2,"dot-size": 4, "halo-size":1,"values":['+ElementValues[sIndicator].join(',')+']';
           YAxiss[iCurIndicator]='"y_axis":{"max":'+(YAxisLabels[sIndicator].length-1)+',"x_offset":'+10+',"step":2,"colour":"'+getChartColor(iCurIndicator)+'","labels":["'+YAxisLabels[sIndicator].join('","')+'"]}';
           var s='<p style=" margin:6px; color:'+getChartColor(iCurIndicator)+'" class="_indicator_text_" >'+vLabCheck[sIndicator]["name"]+'：'+vLabCheck[sIndicator]["intro"]+'</p>';
           ++iCurIndicator;
           if(_createIndicatorText != null) _createIndicatorText(s);
        }
        
        var sYAxis=YAxiss[0];
        var sElements='"elements":[{'+sElementValues.join('},{')+'}]';
        var sXAxis ='"x_axis":{ "max":'+(xLabels.length-0.25*(4-YAxiss.length))+',"offset":'+30*iCurIndicator+',"labels":{"rotate":0,"labels":["'+xLabels.join('","')+'"]}}';
        YAxiss.shift();
        var sYAxiss=',"y_axiss":[{'+YAxiss.join('},{')+'}]';
        if (YAxiss.length==0)
            sYAxiss="";
       
       g_vIndicatorStrs.push('{'+sTitle+','+sXAxis+','+sYAxis+','+sElements+sYAxiss+','+bgcolor+'}');
    }
    return true ;
}
function showIndicatorFlash(id)
{
    if (g_vIndicatorStrs.length<id) 
        return ;
    if (0==id) 
    {
        for(var i=1;i<=g_vIndicatorStrs.length;++i)
        {
            var tmp = _$(getIndicatorFlash()+i);
            if (tmp != null) 
            {
                tmp.style.display="";
                tmp.load(g_vIndicatorStrs[i-1]);
            }
        }
    }
    else
    {
        var tmp = _$(getIndicatorFlash()+id); 
        if (tmp != null) 
        {
            tmp.style.display="";
            try{tmp.load(g_vIndicatorStrs[id-1]);}
            catch(e){}
        }
        
        //document.write(g_vIndicatorStrs[id-1]);
    }
   
}
function loadIndicatorFlashData(id)
{	
	function OnSucc(xmlDoc)
    { 
        g_vIndicatorXmlDoc = xmlDoc ;
        if(!formatIndicatorFlashData()) return ;
        showIndicatorFlash(id);
        if (typeof(g_chartwidth)=="undefined") g_chartwidth=720;
        for(var iCur=2; iCur<=g_vIndicatorStrs.length;++iCur)
        {
            _$(getIndicatorFlash()+(iCur)).style.display="block";
            swfobject.embedSWF("/support/swfchart/open-flash-chart.swf", getIndicatorFlash()+(iCur), g_chartwidth+'', "250","9.0.0", "expressInstall.swf",{'flashready':'OnIndicatorFlashReady','id':''+iCur},{wmode: "transparent"});
        }
    }
    
    function OnFail(xmlDoc)
    {
        alert("获取数据失败");
    }
    if (id == 1)
    {
        getResultXml(g_sUrl,OnSucc,OnFail,OnFail);
    }
    else if (id <= g_vIndicatorStrs.length) 
    {
          var tmp = _$("indicatorchart"+id); 
          showIndicatorFlash(id);
    }
}
function showIndicatorFlashMode(i,dStart,dEnd)
{
    var enddate = g_vNow;
    var startdate;
    switch(i)
    {
        case 1:startdate = getPreBeginMonthDate(enddate,3);break;
        case 2:startdate = getPreBeginMonthDate(enddate,6);break;
        case 3:startdate = getPreBeginMonthDate(enddate,12);break;
        case 4:startdate = getPreBeginMonthDate(enddate,36);break;
        case 5:
            startdate = dStart < dEnd ?　dStart : dEnd ;
            enddate = dStart  > dEnd ?　dStart : dEnd ;
            if (startdate==enddate) 
            {
                alert("起始日期和终止日期相同");
                return ;
            }
        default:break;
    } 
    if(!formatIndicatorFlashData(startdate,enddate, true)) return ;
    showIndicatorFlash(0);
}
